﻿<?xml version="1.0" encoding="utf-8"?><Articles><Article><ArticlesID>611</ArticlesID><Title>Lưu trữ v&amp;#224; hiển thị h&amp;#236;nh ảnh trong Database - ASP.NET</Title><Body>&amp;lt;p&amp;gt;Đầu ti&amp;amp;ecirc;n l&amp;amp;agrave; phải thiết kế CSDL, ở đay t&amp;amp;ocirc;i tạo 1 database mới c&amp;amp;oacute; t&amp;amp;ecirc;n l&amp;amp;agrave; Employee&amp;lt;/p&amp;gt;
&amp;lt;pre title=&amp;quot;code&amp;quot; class=&amp;quot;brush: sql;&amp;quot;&amp;gt;
CREATE DATABASE [Employee]
GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)&amp;lt;/pre&amp;gt;
&amp;lt;p&amp;gt;B1:&amp;amp;nbsp;Tạo 1 Website mới v&amp;amp;agrave; Import Namespace System.Data.SqlClient d&amp;amp;ugrave;ng để truy xuất CSDL&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;B2: V&amp;amp;agrave;o Design k&amp;amp;eacute;o tha 2 Label &amp;amp;amp;&amp;amp;nbsp;1 Textbox Control +&amp;amp;nbsp;1 File Upload Control +&amp;amp;nbsp;1 Image Control (để hiển thị h&amp;amp;igrave;nh ảnh sau khi Upload)&amp;lt;/p&amp;gt;
&amp;lt;pre title=&amp;quot;code&amp;quot; class=&amp;quot;brush: xhtml;&amp;quot;&amp;gt;
&amp;amp;lt;html xmlns=&amp;amp;quot;http://www.w3.org/1999/xhtml&amp;amp;quot;&amp;amp;gt;
&amp;amp;lt;head runat=&amp;amp;quot;server&amp;amp;quot;&amp;amp;gt;
    &amp;amp;lt;title&amp;amp;gt;Save Retrieve Images&amp;amp;lt;/title&amp;amp;gt;
&amp;amp;lt;/head&amp;amp;gt;
&amp;amp;lt;body&amp;amp;gt;
    &amp;amp;lt;form id=&amp;amp;quot;form1&amp;amp;quot; runat=&amp;amp;quot;server&amp;amp;quot;&amp;amp;gt;
    &amp;amp;lt;div&amp;amp;gt;
   
        &amp;amp;lt;asp:Label ID=&amp;amp;quot;lblEmpName&amp;amp;quot; runat=&amp;amp;quot;server&amp;amp;quot; Text=&amp;amp;quot;Employee Name&amp;amp;quot;&amp;amp;gt;&amp;amp;lt;/asp:Label&amp;amp;gt;
&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;
        &amp;amp;lt;asp:TextBox ID=&amp;amp;quot;txtEName&amp;amp;quot; runat=&amp;amp;quot;server&amp;amp;quot;&amp;amp;gt;&amp;amp;lt;/asp:TextBox&amp;amp;gt;
        &amp;amp;lt;br /&amp;amp;gt;
        &amp;amp;lt;asp:Label ID=&amp;amp;quot;lblImage&amp;amp;quot; runat=&amp;amp;quot;server&amp;amp;quot; Text=&amp;amp;quot;Employee Image&amp;amp;quot;&amp;amp;gt;&amp;amp;lt;/asp:Label&amp;amp;gt;
&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;
        &amp;amp;lt;asp:FileUpload ID=&amp;amp;quot;imgUpload&amp;amp;quot; runat=&amp;amp;quot;server&amp;amp;quot; /&amp;amp;gt;
        &amp;amp;lt;br /&amp;amp;gt;
        &amp;amp;lt;br /&amp;amp;gt;
        &amp;amp;lt;asp:Button ID=&amp;amp;quot;btnSubmit&amp;amp;quot; runat=&amp;amp;quot;server&amp;amp;quot; onclick=&amp;amp;quot;btnSubmit_Click&amp;amp;quot;
            Text=&amp;amp;quot;Submit&amp;amp;quot; /&amp;amp;gt;
   
    &amp;amp;amp;nbsp;&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;&amp;amp;amp;nbsp;&amp;amp;amp;nbsp        &amp;amp;lt;asp:Label ID=&amp;amp;quot;lblResult&amp;amp;quot; runat=&amp;amp;quot;server&amp;amp;quot; ForeColor=&amp;amp;quot;#0066FF&amp;amp;quot;&amp;amp;gt;&amp;amp;lt;/asp:Label&amp;amp;gt;
    &amp;amp;lt;br /&amp;amp;gt;
    &amp;amp;lt;hr /&amp;amp;gt;
  
   &amp;amp;lt;asp:Image ID=&amp;amp;quot;Image1&amp;amp;quot; style=&amp;amp;quot;width:200px&amp;amp;quot; Runat=&amp;amp;quot;server&amp;amp;quot; /&amp;amp;gt;
    &amp;amp;lt;/div&amp;amp;gt;
    &amp;amp;lt;/form&amp;amp;gt;
&amp;amp;lt;/body&amp;amp;gt;
&amp;amp;lt;/html&amp;amp;gt;&amp;lt;/pre&amp;gt;
&amp;lt;p&amp;gt;B3: Viết sự kiện Click cho btnSubmit&amp;lt;/p&amp;gt;
&amp;lt;pre title=&amp;quot;code&amp;quot; class=&amp;quot;brush: csharp;&amp;quot;&amp;gt;
protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SqlConnection connection = null;
        try
        {
            FileUpload img = (FileUpload)imgUpload;
            Byte[] imgByte = null;
            if (img.HasFile &amp;amp;amp;&amp;amp;amp; img.PostedFile != null)
            {
                //To create a PostedFile
                HttpPostedFile File = imgUpload.PostedFile;
                //Create byte Array with file len
                imgByte = new Byte[File.ContentLength];
                //force the control to load data in array
                File.InputStream.Read(imgByte, 0, File.ContentLength);
            }
            // Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings [&amp;amp;quot;EmployeeConnString&amp;amp;quot;].ConnectionString;
            connection = new SqlConnection(conn);
 
            connection.Open();
string sql = &amp;amp;quot;INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY&amp;amp;quot;;
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue(&amp;amp;quot;@enm&amp;amp;quot;, txtENaText.Trim());
            cmd.Parameters.AddWithValue(&amp;amp;quot;@eimg&amp;amp;quot;, imgByte);
            int id = Convert.ToInt32(cmd.ExecuteScalar());
            lblResult.Text = String.Format(&amp;amp;quot;Employee ID is {0}&amp;amp;quot;, id);
        }
        catch
        {
            lblResult.Text = &amp;amp;quot;There was an error&amp;amp;quot;;
        }
        finally
        {
            connection.Close();
        }
 
    }&amp;lt;/pre&amp;gt;
&amp;lt;p&amp;gt;B4:&amp;amp;nbsp;Bạn Click chuột phải v&amp;amp;agrave;o Website tạo 1 file &amp;lt;font size=&amp;quot;2&amp;quot;&amp;gt;&amp;lt;font face=&amp;quot;Verdana&amp;quot;&amp;gt;Generic Handler c&amp;amp;oacute; t&amp;amp;ecirc;n l&amp;amp;agrave; &amp;lt;/font&amp;gt;&amp;lt;/font&amp;gt;&amp;lt;font size=&amp;quot;2&amp;quot;&amp;gt;&amp;lt;font face=&amp;quot;Verdana&amp;quot;&amp;gt;ShowImage.ashx chẳng hạn &amp;lt;br /&amp;gt;
&amp;lt;/font&amp;gt;&amp;lt;/font&amp;gt;&amp;lt;/p&amp;gt;
&amp;lt;pre title=&amp;quot;code&amp;quot; class=&amp;quot;brush: csharp;&amp;quot;&amp;gt;
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
 
public class ShowImage : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
       Int32 empno;
       if (context.Request.QueryString[&amp;amp;quot;id&amp;amp;quot;] != null)
            empno = Convert.ToInt32(context.Request.QueryString[&amp;amp;quot;id&amp;amp;quot;]);
       else
            throw new ArgumentException(&amp;amp;quot;No parameter specified&amp;amp;quot;);
 
       context.Response.ContentType = &amp;amp;quot;image/jpeg&amp;amp;quot;;
       Stream strm = ShowEmpImage(empno);
       byte[] buffer = new byte[4096];
       int byteSeq = strm.Read(buffer, 0, 4096);
 
       while (byteSeq &amp;amp;gt; 0)
       {
           context.Response.OutputStream.Write(buffer, 0, byteSeq);
           byteSeq = strm.Read(buffer, 0, 4096);
       }       
       //context.Response.BinaryWrite(buffer);
    }
 
    public Stream ShowEmpImage(int empno)
    {
 string conn = ConfigurationManager.ConnectionStrings     [&amp;amp;quot;EmployeeConnString&amp;amp;quot;].ConnectionString;
        SqlConnection connection = new SqlConnection(conn);
        string sql = &amp;amp;quot;SELECT empimg FROM EmpDetails WHERE empid = @ID&amp;amp;quot;;
        SqlCommand cmd = new SqlCommand(sql,connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue(&amp;amp;quot;@ID&amp;amp;quot;, empno);
        connection.Open();
        object img = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])img);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
 
 
}&amp;lt;/pre&amp;gt;
&amp;lt;p&amp;gt;File n&amp;amp;agrave;y c&amp;amp;oacute; nhiệm vụ Request thằng ID tr&amp;amp;ecirc;n QueryString để SELECT&amp;amp;nbsp;trong bảng EmpDetail v&amp;amp;agrave; lấy về trường Image v&amp;amp;agrave; g&amp;amp;aacute;n n&amp;amp;oacute; v&amp;amp;agrave;o 1 Stream c&amp;amp;oacute; t&amp;amp;ecirc;n l&amp;amp;agrave; ShowEmpImage. Từ Stream đ&amp;amp;oacute; th&amp;amp;igrave; qu&amp;amp;aacute; dễ để bạn Write ra file ảnh jpg hoặc gif r&amp;amp;ugrave;i&amp;amp;nbsp;&amp;lt;img alt=&amp;quot;&amp;quot; src=&amp;quot;http://dev.meotom.net/Library/Editor/fckeditor/editor/images/smiley/yahoo/4.gif&amp;quot; /&amp;gt;&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;B5 Bước cuối c&amp;amp;ugrave;ng:&amp;amp;nbsp;trong sự kiện btnSubmit_Click (d&amp;amp;ograve;ng trước Catch)&amp;amp;nbsp;bạn set lại thuộc t&amp;amp;iacute;nh ImageURL cho Control Image1&amp;lt;/p&amp;gt;
&amp;lt;pre title=&amp;quot;code&amp;quot; class=&amp;quot;brush: csharp;&amp;quot;&amp;gt;
Image1.ImageUrl = &amp;amp;quot;~/ShowImage.ashx?id=&amp;amp;quot; + id;&amp;lt;/pre&amp;gt;
&amp;lt;p&amp;gt;Download Source Code &amp;lt;a href=&amp;quot;http://dev.meotom.net/Uploads/admin/2009/11/13/ReadWriteImages.zip&amp;quot;&amp;gt;tại đ&amp;amp;acirc;y&amp;lt;/a&amp;gt;.&amp;lt;/p&amp;gt;
&amp;lt;p&amp;gt;Theo dotnetcurry.&amp;lt;/p&amp;gt;</Body><CommentEnabled>True</CommentEnabled><ViewCount>0</ViewCount><ReleaseDate>11/13/2009 10:12:27 AM</ReleaseDate><TotalComment>0</TotalComment><IsMedia>False</IsMedia><IsPicture>False</IsPicture><IsVote>True</IsVote><ArticlePassword /><PostVisible>0</PostVisible><ArticlePath>/2009/11/13/Luu-tru-va-hien-thi-hinh-anh-trong-Database---ASP-NET-263</ArticlePath><Approved>True</Approved><ImagePath /><CategoryId>26</CategoryId><ArrayCatID>26|25</ArrayCatID></Article></Articles>